from app.core import controller
from app.core import mysql
from app.chat.consumers import UserSpecificConsumer

controllerClass = getattr(controller, "Controller")


# 用户聊天好友
class User_chat_friend(controllerClass):
    def __init__(self, config={}):
        """
        构造函数
        @param {Object} config 配置参数
        """
        config_init = {
            # 选择的模板那路径模板
            "tpl": "./user_chat_friend/",
            # 选择的服务
            "service": "user_chat_friend",
            "get_api": ["get_friend_list", "del_friend", "get_add_friend_list", "get_read_list"],
            "post_api": ["add_friend"]
        }
        config_temp = config
        config_temp.update(config_init)
        super(User_chat_friend, self).__init__(config_temp)

    def Get_friend_list(self, ctx):
        """查询用户好友"""

        query = dict(ctx.query)
        user_id = query.get("user_id")

        if not user_id:
            return {"result": {"list": []}}

        sql = """
            SELECT
                t1.user_chat_friend_id,
                t1.user_id,
                t1.friend_user_id,
                t1.friend_user_name,
                t1.create_time,
                t1.update_time,
                t2.username,
                t2.nickname,
                t2.avatar
            FROM user_chat_friend t1
            LEFT JOIN `user` t2 ON t1.friend_user_id = t2.user_id
            WHERE t1.user_id = %s
            """ % (user_id)

        result = mysql.Service.run(self, sql=sql)

        return {"result": {"list": result if result else []}}

    def Add_friend(self, ctx):
        """新增用户好友"""

        body = ctx.body
        user_id = body["user_id"]

        sql_username = '''SELECT username FROM `user` WHERE user_id = %s''' % (user_id)
        username = mysql.Service.run(self, sql=sql_username)

        new_body = {
            "user_id": body["friend_user_id"],
            "friend_user_id": body["user_id"],
            "friend_user_name": username[0]["username"]
        }

        avatar = body["avatar"]

        del body["friend_user_name"]
        del body["avatar"]

        sql = "SELECT count(1) as count FROM  user_chat_friend WHERE user_id = " + str(
            body["user_id"]) + " and friend_user_id = " + str(body["friend_user_id"])
        count = mysql.Service.run(self, sql=sql)

        if count[0]['count'] <= 0:
            self.service.Add(ctx.body, self.config)

        new_sql = "SELECT count(1) as count FROM  user_chat_friend WHERE user_id = " + str(
            new_body["user_id"]) + " and friend_user_id = " + str(new_body["friend_user_id"])
        new_count = mysql.Service.run(self, sql=new_sql)

        if new_count[0]['count'] <= 0:
            self.service.Add(new_body, self.config)

        # 发送WebSocket通知
        UserSpecificConsumer.send_message_to(
            body["user_id"],
            {
                "message_type": 5,
                "user_id": body["friend_user_id"],
                "username": username,
                "avatar": avatar
            }
        )

        return {"result": 1}

    def Del_friend(self, ctx):
        """删除用户好友"""

        query = dict(ctx.query)
        friend_user_id = query.get("friend_user_id")
        user_id = query.get("user_id")

        if not all([friend_user_id, user_id]):
            return {"result": 1}

        # 删除正向关系
        self.service.Del({"friend_user_id": friend_user_id, "user_id": user_id}, self.config)

        # 删除反向关系
        result = self.service.Del({"user_id": friend_user_id, "friend_user_id": user_id}, self.config)

        # 发送WebSocket通知
        UserSpecificConsumer.send_message_to(
            friend_user_id,
            {
                "message_type": 5,
                "user_id": user_id
            }
        )

        return {"result": result if result > 0 else 0}

    def Get_add_friend_list(self, ctx):
        """查询可添加的好友"""
        query = dict(ctx.query)
        user_id = query.get("user_id")

        if not user_id:
            return {"result": {"list": []}}

        sql = """
            SELECT *
            FROM `user`
            WHERE user_id NOT IN (
                SELECT friend_user_id
                FROM user_chat_friend
                WHERE user_id = %s
            )
        """ % (user_id)

        result = self.service.run(sql=sql)

        return {"result": {"list": result if result else []}}

    def Get_read_list(self, ctx):
        """查询用户好友未读"""

        query = dict(ctx.query)
        user_id = query.get("user_id")
        send_user_id = query.get("send_user_id")

        if not all([user_id, send_user_id]):
            return {"result": {"list": []}}

        sql = """
            SELECT
                user_chat_read_id,
                user_id,
                send_user_id,
                group_id,
                `type`,
                create_time,
                message
            FROM user_chat_read
            WHERE
                user_id = %s AND
                send_user_id = %s AND
                `type` = 1
            ORDER BY create_time ASC
        """ % (user_id, send_user_id)

        result = self.service.run(sql=sql)

        return {"result": {"list": result if result else []}}




